package com.example.shuiyin.service.impl;

import com.example.shuiyin.entity.AvatarHistory;
import com.example.shuiyin.entity.User;
import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import com.example.shuiyin.mapper.UserMapper;
import com.example.shuiyin.service.AvatarService;
import com.example.shuiyin.service.MinioStorageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AvatarServiceImpl implements AvatarService {

    private final MinioStorageService minioStorageService;
    private final UserMapper userMapper;

    @Override
    @Transactional
    public String uploadAvatar(Long userId, MultipartFile file) throws IOException {
        log.info("为用户 {} 上传新头像", userId);
        
        try {
            // 1. 验证用户存在
            User user = userMapper.selectById(userId);
            if (user == null) {
                throw new AppException("用户不存在", ErrorCode.USER_NOT_FOUND);
            }
            
            // 2. 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = "avatar_" + userId + "_" + System.currentTimeMillis() + extension;
            
            // 3. 上传到MinIO
            String objectName = "avatars/" + userId + "/" + uniqueFilename;
            minioStorageService.uploadFile(file, objectName);
            
            // 4. 使用固定长度的相对路径
            String relativePath = "/api/avatars/" + userId + "/current";
            
            // 5. 更新用户头像信息
            user.setAvatar(uniqueFilename);
            user.setAvatarUrl(relativePath);
            
            // 6. 使用try-catch特别处理数据库更新异常
            try {
                userMapper.updateById(user);
            } catch (Exception dbException) {
                log.error("数据库更新失败，可能是avatar_url字段长度不足: {}", dbException.getMessage());
                // 尝试使用更短的值
                user.setAvatarUrl("/avatar/" + userId);
                userMapper.updateById(user);
            }
            
            log.info("用户 {} 的新头像上传成功: {}", userId, relativePath);
            return relativePath;
        } catch (Exception e) {
            log.error("上传头像失败: {}", e.getMessage(), e);
            if (e instanceof AppException) {
                throw e;
            }
            throw new IOException("上传头像失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<AvatarHistory> getUserAvatarHistory(Long userId) {
        log.info("获取用户 {} 的头像历史", userId);
        
        // 验证用户存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.warn("尝试获取不存在用户的头像历史: {}", userId);
            return Collections.emptyList();
        }
        
        try {
            // 这里需要根据实际情况实现
            // 由于没有实际的AvatarHistoryMapper，这里返回一个空列表
            // 在实际实现中，您应该从数据库中查询用户的头像历史
            log.info("由于缺少AvatarHistoryMapper实现，返回空列表");
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("获取用户头像历史失败: {}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    @Override
    @Transactional
    public String setActiveAvatar(Long userId, Long avatarHistoryId) {
        log.info("设置用户 {} 的活跃头像为 {}", userId, avatarHistoryId);
        
        // 验证用户存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new AppException("用户不存在", ErrorCode.USER_NOT_FOUND);
        }
        
        // 这里需要根据实际情况实现
        // 由于没有实际的AvatarHistoryMapper，这里简单返回当前头像URL
        // 在实际实现中，您应该查询特定的头像历史记录，并将其设置为活跃
        log.info("由于缺少AvatarHistoryMapper实现，返回当前头像URL");
        return user.getAvatarUrl();
    }

    @Override
    @Transactional
    public boolean deleteAvatar(Long userId, Long avatarId) {
        log.info("删除用户 {} 的头像 {}", userId, avatarId);
        
        // 验证用户存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new AppException("用户不存在", ErrorCode.USER_NOT_FOUND);
        }
        
        // 查找头像文件名
        // 注意：在实际情况下，您可能需要从数据库查询头像历史记录
        // 这里简化实现，直接构建文件名
        String avatarFilename = "avatar_" + userId + "_" + avatarId;
        
        try {
            // 从MinIO中删除文件
            minioStorageService.deleteFile("avatars/" + userId, avatarFilename);
            
            log.info("成功删除用户 {} 的头像 {}", userId, avatarId);
            return true;
        } catch (Exception e) {
            log.error("删除头像失败: {}", e.getMessage(), e);
            throw new AppException("删除头像失败: " + e.getMessage(), ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }
} 